import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { userList, userDocument } from '../../schemas/user.schema';

@Injectable()
export class UserService {
  constructor(
    @InjectModel(userList.name) private userModel: Model<userDocument>,
  ) {}
  async findUserById(id: string) {
    try {
      const users = await this.userModel.find({
        _id: id,
      });
      return users[0];
    } catch (error) {
      return {};
    }
  }

  async findUserByName(name: string) {
    try {
      const users = await this.userModel.find({
        username: name,
      });
      return users;
    } catch (error) {
      return [];
    }
  }

  async registeredUsers(user: any) {
    try {
      // 判断是否存在username
      const users = await this.userModel.find({
        username: user.username,
      });
      if (users.length > 0) {
        return { code: 500, message: '用户名已存在' };
      }
      const addInfo = await this.userModel.create(user);
      // 如果添加操作没有返回_id，表示添加失败
      if (!addInfo._id) {
        return { code: 500, message: '添加失败' };
      }
      // 添加成功，返回成功信息及用户ID
      return { code: 200, message: '添加成功', data: addInfo._id };
    } catch (error) {
      // 可以考虑更详细的错误处理逻辑
      console.error('添加用户时发生错误:', error);
      return { code: 500, message: '服务器内部错误' };
    }
  }

  async changeStatus(id: string, state: string) {
    const userOptionsState = ['0', '1', '2'];
    // 校验数据
    if (!id || !state || !userOptionsState.includes(state)) {
      return { code: 500, message: '参数错误', data: false };
    }
    try {
      const findUser = await this.userModel.find({ _id: id });
      if (findUser.length === 0) {
        return { code: 500, message: '用户不存在', data: false };
      }
      if (findUser.length > 1) {
        return { code: 500, message: '用户信息异常', data: false };
      }
      if (findUser[0].state === Number(state)) {
        return { code: 500, message: '用户状态已存在', data: false };
      }
      const updateInfo: any = await this.userModel.updateOne(
        { _id: id },
        { state: state },
      );
      if (updateInfo.nModified === 0) {
        return { code: 500, message: '更新失败', data: false };
      }
      return { code: 200, message: '更新成功', data: true };
    } catch (error) {
      return { code: 500, message: '服务器内部错误' };
    }
  }

  async getAllUsers(body: any) {
    let backData = {};
    try {
      if (!body.userState) {
        backData = {
          code: 200,
          data: {
            total: await this.userModel.countDocuments(),
            rows: await this.userModel
              .find()
              .skip((body.page - 1) * body.pageSize)
              .limit(body.pageSize)
              .exec(),
          },
        };
        return;
      }
      const userList = await this.userModel
        .find({
          state: body.userState,
        })
        .skip((body.page - 1) * body.pageSize)
        .limit(body.pageSize)
        .exec();

      backData = {
        code: 200,
        data: {
          total: await this.userModel.countDocuments({
            state: body.userState,
          }),
          rows: userList,
        },
      };
    } catch (error) {
      backData = { code: 500, message: '服务器内部错误' };
    } finally {
      return backData;
    }
  }
}
